package com.sttg.csp.common.action;

import java.util.HashMap;
import java.util.Map;
import com.sttg.csp.common.consts.SystemConst;
import com.sttg.csp.common.exception.BizException;
import com.sttg.csp.common.service.LoginService;


/**
 * 
 * This Action is responsable to deal with login
 */
public class LoginAction extends PagedAction {

	private Map model;
	
	private LoginService loginService = LoginService.getInstance();

	public LoginAction() {
		super();
	}

	// Show landing page
	public String showLogin() throws Exception {
		return SUCCESS;
	}

	// Response the request of login
	public String doLogin() throws Exception {
		try {
			logger.debug("output user info: " + model);
			Map user = loginService.doUserLogin(model);
			
			Map<String, String> unitedUser = new HashMap<String, String>();
			String userType = (String) model.get("USER_TYPE");
			
			String sessionUid = "";
			String sessionUserName = "";
			String sessionDepartment = "";
			if ("1".equals(userType)) {
				sessionUid = (String) model.get("BD_UID");
			} else if ("2".equals(userType)) {
				// current user is B/D admin
				sessionUid = (String) user.get("DP_USER_ID");
				sessionUserName = (String) user.get("BD_ADMIN_NAME");
				sessionDepartment = (String) user.get("DEPARTMENT");
				
			} else if ("3".equals(userType)) {
				//current user is B/D user
				sessionUid = (String) user.get("BD_USER_ID");
				sessionUserName = (String) user.get("BD_USER_NAME");
				sessionDepartment = (String) user.get("DEPARTMENT");
				
			}
			unitedUser.put("SESSION_UID", sessionUid);
			unitedUser.put("SESSION_USER_NAME", sessionUserName);
			unitedUser.put("SESSION_DEPARTMENT", sessionDepartment);
			unitedUser.put("SESSION_USER_TYPE", userType);
			
			session.put(SystemConst.SESSION_USER, unitedUser);
		} catch (BizException e) {
			this.addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}

	// Show main page
	public String showMain() {
		return SUCCESS;
	}
	
	// Response that user logout system
	public String doLogout() throws Exception {
		getSession().clear();	//clear session info of current b/d user.
		return SUCCESS;
	}

	
	public Map getModel() {
		return model;
	}

	public void setModel(Map model) {
		this.model = model;
	}

}
